package logging

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"encoding/json"
	"fmt"

	"github.com/go-logr/logr"
	"github.com/rs/zerolog"
)

func NewLogrAdapter(z *zerolog.Logger) logr.Logger {
	l := logr.New(newLogrSinkAdapter(z))
	l.V(int(z.GetLevel()))
	return l
}

// logrSinkAdapter implements logr.Logger interface.
// The adapter allows us to encapsulate zerolog into go-logr/logr interface.
type logrSinkAdapter struct {
	z             *zerolog.Logger
	keysAndValues map[string]string
	name          string
}

func newLogrSinkAdapter(z *zerolog.Logger) *logrSinkAdapter {
	kv := make(map[string]string)
	return &logrSinkAdapter{
		z,
		kv,
		"",
	}
}

func (a *logrSinkAdapter) Init(_ logr.RuntimeInfo) {

}

func (a *logrSinkAdapter) Enabled(_ int) bool {
	return true
}

func (a *logrSinkAdapter) Info(_ int, msg string, keysAndValues ...interface{}) {
	a.WithValues(keysAndValues)
	if a.name != "" {
		a.z.Info().Msgf("%s: %s %s", a.name, msg, a.valuesAsJSON())
		return
	}
	a.z.Info().Msgf("%s %s", msg, a.valuesAsJSON())
}

func (a *logrSinkAdapter) Error(err error, msg string, keysAndValues ...interface{}) {
	a.WithValues(keysAndValues)
	if a.name != "" {
		a.z.Err(err).Msgf("%s: %s %s", a.name, msg, a.valuesAsJSON())
		return
	}
	a.z.Err(err).Msgf("%s %s", msg, a.valuesAsJSON())
}

func (a *logrSinkAdapter) WithValues(keysAndValues ...interface{}) logr.LogSink {
	newKV := make(map[string]string)
	for k, v := range a.keysAndValues {
		newKV[k] = v
	}
	for i := 0; i < len(keysAndValues)/2; i++ {
		keyIndex := i * 2
		valIndex := keyIndex + 1
		if valIndex >= len(keysAndValues) {
			continue
		}
		key := fmt.Sprintf("%v", keysAndValues[keyIndex])
		value := fmt.Sprintf("%v", keysAndValues[valIndex])
		newKV[key] = value
	}
	return &logrSinkAdapter{
		z:             a.z,
		keysAndValues: newKV,
		name:          a.name,
	}
}

func (a *logrSinkAdapter) WithName(name string) logr.LogSink {
	newKV := make(map[string]string)
	for k, v := range a.keysAndValues {
		newKV[k] = v
	}
	return &logrSinkAdapter{
		z:             a.z,
		keysAndValues: newKV,
		name:          a.name + "/" + name,
	}
}

func (a *logrSinkAdapter) valuesAsJSON() (s string) {
	var b []byte
	b, _ = json.Marshal(a.keysAndValues)
	s = string(b)
	return s
}
